package com.lzh.rocblogbackend.controller;

import com.lzh.rocblogbackend.common.AjaxResult;
import com.lzh.rocblogbackend.mapper.CommentMapper;
import com.lzh.rocblogbackend.mapper.ReplyMapper;
import com.lzh.rocblogbackend.model.Comment;
import com.lzh.rocblogbackend.model.Reply;
import com.lzh.rocblogbackend.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;

@RestController
public class CommentController {
    @Autowired
    ReplyMapper replyMapper;
    @Autowired
    CommentMapper commentMapper;
    @RequestMapping("/upload/comment")
    public HashMap<String,Object> uploadComment(String content,String email,String qq,int blogId) {
        //获取QQ头像
        String headshot="http://q1.qlogo.cn/g?b=qq&nk="+qq+"&s=100";
        //获取QQ昵称
        RestTemplate restTemplate=new RestTemplate();
        String accessToken = "fakeAT";
        String nickname = restTemplate.getForEntity("https://api.kuizuo.cn/api/qqnick?qq="+qq,
                String.class,accessToken).getBody();
        if(nickname.length()>10&&nickname.substring(nickname.indexOf("statusCode")+12,nickname.indexOf("statusCode")+15).equals("500")) {
            return AjaxResult.fail(501,"QQ号码错误");
        }
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setEmail(email);
        comment.setHeadshot(headshot);
        comment.setNickname(nickname);
        comment.setBlogId(blogId);
        comment.setTime(TimeUtil.getCurrentTime());
        int ret = commentMapper.upload(comment);
        if(ret==1) {
            return AjaxResult.success("评论成功",null);
        } else {
            return AjaxResult.fail(-1,"评论失败");
        }
    }
    @RequestMapping("/getcomment")
    public HashMap<String,Object> getComment(int blogId) {
        List<Comment> commentList = commentMapper.getAll(blogId);
        for(int i=0;i<commentList.size();i++) {
            commentList.get(i).setReplyList(getCommentById(commentList.get(i).getId()));
        }
        return AjaxResult.success(commentList);
    }
    public List<Reply> getCommentById(int commentId) {
       return replyMapper.getAll(commentId);
    }
    @RequestMapping("/getcommentnum")
    public HashMap<String,Object> getCommentNum() {
        return AjaxResult.success("评论总量",commentMapper.getNum());
    }
 }
